import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig, RequestConfig } from 'umi';
import { RequestOptionsInit } from 'umi-request';
import { history } from 'umi';
import {  notification,Image } from 'antd';

import Footer from '@/components/Footer';
import Header from '@/components/Header';

import TabLayout from '@/components/PageTab/TabLayout';
import { currentUser as queryCurrentUser } from './services/user';
import { queryMenuTree } from './services/module'

import WebsocketHeartbeatJs from 'websocket-heartbeat-js';
import { queryAllDict } from '@/services/dict';
import 'moment/locale/zh-cn';
import locale from 'antd/lib/locale/zh_CN';

import { queryDeviceAlarmNotices} from '@/services/deviceAlarm';
//本地
// const serverUrl="172.16.99.188:8080"
//发布需要改为IP

//const serverUrl="172.16.98.25:80"


import {
  BankOutlined,
  ProfileOutlined,
  TableOutlined,
  CodepenOutlined,
  RobotOutlined,
  CarryOutOutlined,
  UserOutlined,
  SolutionOutlined,
  TeamOutlined,
  CommentOutlined,
  SettingOutlined,
  BarsOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';

// 利用对象进行图标映射
const iconMapping = {
  BankOutlined: <BankOutlined />,
  ProfileOutlined: <ProfileOutlined />,
  TableOutlined: <TableOutlined />,
  CodepenOutlined: <CodepenOutlined />,
  RobotOutlined: <RobotOutlined />,
  CarryOutOutlined: <CarryOutOutlined />,
  UserOutlined: <UserOutlined />,
  SolutionOutlined: <SolutionOutlined />,
  TeamOutlined: <TeamOutlined />,
  CommentOutlined: <CommentOutlined />,
  SettingOutlined: <SettingOutlined />,
  BarsOutlined: <BarsOutlined />,
  ApartmentOutlined: <ApartmentOutlined />,
}

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  mySocket?: WebsocketHeartbeatJs;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  dicts?:any;
  alarmNotices?:any;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser() as API.ErrorResponse;

      if (msg.errorCode === '401') {
        history.push(loginPath+"?redirect="+history.location.pathname);
      }
      return msg as API.CurrentUser;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    console.log(currentUser)
    //获取字典信息保存本地
    const dicts = await queryAllDict();
    const alarmNotices = await queryDeviceAlarmNotices({});
    let mySocket=undefined;
    if(currentUser?.serviceUrl!=null){
      mySocket = new WebsocketHeartbeatJs({
        url: 'ws://172.16.99.188:8080/ws/' + currentUser?.userId
      });
      
      mySocket.onopen = function () {
        console.log('connect success');
      }
    }
    return {
      fetchUserInfo,
      currentUser,
      mySocket,
      settings: {},
      dicts,
      alarmNotices
    };
  }
  return {
    fetchUserInfo,
    settings: {}
  };
}

const contextMenuLabels = {
  closeTab: '关闭标签',
  closeRightTabs: '关闭右侧标签',
  closeAllTabs: '关闭所有标签'
}

const onMessage =async  (e:any,setState:any) => {
 console.log(`onmessage: ${e.data}`);
 const data = JSON.parse(e.data);
 if(data.AlarmData){
 await setState((s) => ({ ...s, alarmNotices: data.AlarmData }));
}
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState,setInitialState }) => {
  const { mySocket } = initialState || {};
  return {
    // logo: () => { return <Image src={logo} preview={false} /> },
    // rightContentRender: () => <RightContent />,
    childrenRender: (dom) => {
      if (location.pathname === loginPath) {
        return dom;
      } else {
        if (location.pathname === 'screen'||location.pathname.indexOf("mocha3D")!=-1||location.pathname.indexOf("patrolRecordDetails1")!=-1||location.pathname.indexOf("/device/create")!=-1 ) {
          return dom;
        } else {
          if(mySocket){
            try {
              mySocket.send("removeId");
            } catch (error) {
              console.log(error)
            }
            mySocket.onmessage = function (e) {
              if ("heartbeat" != e.data) {
                onMessage(e,setInitialState);
              }
            }
          }
          return (
            <TabLayout  maxNum={5} locale={locale} {...dom.props} history={history} contextMenuLabels={contextMenuLabels} >
              {dom}
            </TabLayout>
          );
        }
      }
    },
    menu: {
      params: {
        userId: initialState?.currentUser?.userId,
      },
      request: async (params, defaultMenuData) => {
        const menuData = await queryMenuTree();
        menuData.forEach((item: any) => item.icon = iconMapping[item.icon]);
          return menuData;
      },
    },
    disableContentMargin: true,
    footerRender: () => <Footer />,
    headerRender: () => <Header />,
    onPageChange: () => {
      const { location } = history;
  
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        //history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

/**
 * 异常处理程序
 */
const errorHandler = (error: any): Response => {
  const { response } = error;
  if (response && response.errorCode != '401') {
    notification.error({
      message: `请求错误 ${response.errorCode}`,
      description: response.errorMessage,
    });
  }
  return response;
};

const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  return {
    url: `${url}`,
    options: { ...options },
  };
};

const responseInterceptors = async(response: Response, options: RequestOptionsInit) => {
  const result = await response.clone().json();

  if (result.success && result.data) {
    return result.data;
  }
  return response;
};

export const request: RequestConfig = {
  errorHandler: errorHandler,
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [responseInterceptors],
};